package cn.harry.modular.sys.service.impl;

import cn.harry.common.exception.ApiException;
import cn.harry.modular.sys.exception.enums.SysExceptionEnum;
import cn.harry.modular.sys.mapper.SysDictMapper;
import cn.harry.modular.sys.domain.SysDict;
import cn.harry.modular.sys.service.SysDictService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 数据字典
 *
 * @author honghh Date 2020-03-16 09:53:38 Copyright (C) www.tech-harry.cn
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict>
		implements SysDictService {

	@Override
	public boolean create(SysDict sysDict) {
		if (checkDictTypeUnique(null, sysDict.getType())) {
			throw new ApiException(SysExceptionEnum.DICT_TYPE_EXISTS);
		}
		return save(sysDict);
	}

	@Override
	public int updateDict(SysDict sysDict) {
		if (checkDictTypeUnique(sysDict.getId(), sysDict.getType())) {
			throw new ApiException(SysExceptionEnum.DICT_TYPE_EXISTS);
		}
		return this.baseMapper.updateById(sysDict);
	}

	@Override
	public List<SysDict> getExportList(SysDict sysDict) {
		LambdaQueryWrapper<SysDict> wrapper = new LambdaQueryWrapper<>(sysDict);
		if (StrUtil.isNotEmpty(sysDict.getBeginTime())) {
			wrapper.gt(SysDict::getCreateTime, sysDict.getBeginTime());
		}
		if (StrUtil.isNotEmpty(sysDict.getEndTime())) {
			wrapper.lt(SysDict::getCreateTime, sysDict.getEndTime());
		}
		return list(wrapper);
	}

	/**
	 * 校验字典类型是否唯一
	 * @param id
	 * @param type
	 */
	private boolean checkDictTypeUnique(Long id, String type) {
		Long dictId = id == null ? -1L : id;
		SysDict sysDict = this.baseMapper
				.selectOne(new LambdaQueryWrapper<SysDict>().eq(SysDict::getType, type));
		return sysDict != null && !dictId.equals(sysDict.getId());
	}

}